﻿using ET.Score.Service.Interfaces;
using ET.Score.SharedLibrary.Wcf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Description;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using System.Configuration;

namespace ET.HeartBeat.SharedLibrary
{
    public  class HeartBeatInit
    {
        public static HeartBeatInvoker<IHeartBeatService> MyHeartBeatInvoker;
        /// <summary>
        /// 启动心跳服务
        /// </summary>
        /// <param name="server">心跳回调服务</param>
        /// <param name="IpAdress">WCF心跳地址</param>
        /// <param name="LoginType">登录类型--参考枚举LoginType</param>
        /// <returns></returns>
        public static HeartBeatInvoker<IHeartBeatService> HeartBeatInitService(HeartBeatCallBack server,string IpAdress,string UserName)
        {
            InstanceContext context = new InstanceContext(server);
            NetTcpBinding netTcpBinding = new NetTcpBinding();

            // 设置超时时间（以秒为单位）
            netTcpBinding.SendTimeout = TimeSpan.FromSeconds(30); // 发送超时
            netTcpBinding.ReceiveTimeout = TimeSpan.FromSeconds(30); // 接收超时
            netTcpBinding.OpenTimeout = TimeSpan.FromSeconds(30); // 打开连接超时
            netTcpBinding.CloseTimeout = TimeSpan.FromSeconds(30); // 关闭连接超时

            // 设置安全模式为 None，如果需要加密通信可根据需求调整
            netTcpBinding.Security.Mode = SecurityMode.None;

            // 设置传输模式为 Buffered，可以根据需求选择 Streamed
            netTcpBinding.TransferMode = TransferMode.Buffered;

            // 设置最大接收消息大小为 10MB
            netTcpBinding.MaxReceivedMessageSize = 2147483647; // 10MB in bytes

            // 设置最大缓冲池大小为 524288 bytes (512KB)
            netTcpBinding.MaxBufferPoolSize = 524288;

            // 设置读取配额
            netTcpBinding.ReaderQuotas.MaxStringContentLength = 8192;
            netTcpBinding.ReaderQuotas.MaxArrayLength = 2147483647;

            DuplexChannelFactory<IHeartBeatService> factory = new DuplexChannelFactory<IHeartBeatService>(context, netTcpBinding, new EndpointAddress(IpAdress));
            foreach (OperationDescription op in factory.Endpoint.Contract.Operations)
            {
                DataContractSerializerOperationBehavior dataContractBehavior = op.Behaviors.Find<DataContractSerializerOperationBehavior>() as DataContractSerializerOperationBehavior;
                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = Int32.MaxValue;
                }
            }
            try
            {
                HeartMonitorProvider.UserName = UserName;
                MyHeartBeatInvoker = new ET.Score.SharedLibrary.Wcf.HeartBeatInvoker<IHeartBeatService>(factory, HeartMonitorProvider.HeartBeat);
                MyHeartBeatInvoker.Start();
            }
            catch (Exception ex)
            {

            }
            return MyHeartBeatInvoker;
        }
    }
}
